<template>
    <view class="chat-container">
        <!-- 头部返回 + 用户名 -->
        <view class="chat-header">
            <view @click="goBack" class="back-button">返回</view>
            <text class="chat-name">{{ chatName }}</text>
        </view>

        <!-- 聊天记录 -->
        <scroll-view class="message-list" scroll-y="true" :scroll-top="scrollTop" 
                    :scroll-with-animation="true" @scrolltoupper="loadMoreMessages">
            <!-- 商品信息卡片 -->
                <view v-if="chatInfo && chatInfo.productInfo" class="product-card">
                    <image :src="chatInfo.productInfo.img" class="product-image" mode="aspectFill"/>
                    <view class="product-info">
                        <text class="product-name">{{ chatInfo.productInfo.name }}</text>
                        <text class="product-price">¥{{ chatInfo.productInfo.price }}</text>
                        <button class="order-btn" @tap="placeOrder">立即下单</button>
                    </view>
                </view>

            <!-- 消息列表 -->
            <view v-for="(message, index) in messageList" :key="index" 
                  :class="['message-item', message.isSelf ? 'message-self' : 'message-other']">
                <image v-if="!message.isSelf" :src="chatInfo.sellerAvatar || '/static/default-avatar.png'" class="avatar"/>
                <view class="message-content">
                    <text v-if="message.type === 'text'" class="text-message">{{ message.content }}</text>
                    <image v-else-if="message.type === 'image'" 
                           :src="message.url" 
                           class="image-message" 
                           mode="widthFix"
                           @tap="previewImage(message.url)"/>
                </view>
                <image v-if="message.isSelf" :src="userInfo.avatarUrl" class="avatar"/>
            </view>
        </scroll-view>

        <!-- 输入框区域 -->
        <view class="input-area">
            <view class="input-container">
                <textarea v-model="messageText" 
                         class="message-input" 
                         :adjust-position="false"
                         :cursor-spacing="20"
                         :show-confirm-bar="false"
                         :fixed="true"
                         auto-height
                         placeholder="输入消息..."/>
                <view class="button-group">
                    <view @tap="chooseImage" class="icon-button">
                        <text class="icon">图片</text>
                    </view>
                    <view @tap="sendMessage" class="send-button" :class="{ 'active': messageText.trim() }">
                        发送
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import messageApi from '@/utils/api.js';

export default {
    name: "ChatDetail",
    data() {
        return {
            chatInfo: {
                sellerId: '',
                sellerName: '',
                sellerAvatar: '',
                productInfo: {
                    id: '',
                    name: '',
                    img: '',
                    price: '',
                    brief: '',
                    delivery: ''
                }
            },
            chatName: "",
            messageList: [],
            messageText: "",
            scrollTop: 0,
            userInfo: {
                avatarUrl: uni.getStorageSync('userInfo')?.avatarUrl || '/static/default-avatar.png'
            }
        };
    },
    onLoad() {
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('chatInfo', (data) => {
            // 确保数据完整性
            this.chatInfo = {
                sellerId: data.sellerId || '',
                sellerName: data.sellerName || '',
                sellerAvatar: data.sellerAvatar || '',
                productInfo: {
                    id: data.productInfo?.id || '',
                    name: data.productInfo?.name || '',
                    img: data.productInfo?.img || '',
                    price: data.productInfo?.price || '',
                    brief: data.productInfo?.brief || '',
                    delivery: data.productInfo?.delivery || ''
                }
            };
            this.chatName = data.sellerName || '';
            
            // 添加系统消息
            if (data.productInfo?.name) {
                this.messageList = [{
                    type: 'text',
                    content: `我对"${data.productInfo.name}"感兴趣`,
                    time: new Date().getTime(),
                    isSelf: true
                }];
            }
            
            // 从本地存储加载历史消息
            this.loadHistoryMessages();
            
            // 更新消息列表
            this.updateChatList();
        });
    },
    methods: {
		// 添加下单方法
		        placeOrder() {
		                    uni.showModal({
		                        title: '确认下单',
		                        content: `是否确认购买 ${this.chatInfo.productInfo.name}？`,
		                        success: (res) => {
		                            if (res.confirm) {
		                                // 发起下单请求
		                                uni.request({
		                                    url: this.baseUrl + '/wx/order/submit',
		                                    method: 'POST',
		                                    header: {
		                                        'content-type': 'application/json',
		                                        'X-Token': uni.getStorageSync('token')
		                                    },
		                                    data: {
		                                        productId: this.chatInfo.productInfo.id,
		                                        sellerId: this.chatInfo.sellerId,
		                                        price: this.chatInfo.productInfo.price
		                                    },
		                                    success: (response) => {
		                                        if (response.statusCode === 200 && response.data.errno === 0) {
		                                            const orderId = response.data.data;
		                                            // 下单成功后，发起支付
		                                            this.requestPayment(orderId);
		                                        } else {
		                                            uni.showToast({
		                                                title: response.data.errmsg || '下单失败',
		                                                icon: 'none'
		                                            });
		                                        }
		                                    },
		                                    fail: (error) => {
		                                        console.error('下单失败:', error);
		                                        uni.showToast({
		                                            title: '下单失败',
		                                            icon: 'none'
		                                        });
		                                    }
		                                });
		                            }
		                        }
		                    });
		                },
		        
		                requestPayment(orderId) {
		                    // 获取支付参数
		                    uni.request({
		                        url: this.baseUrl + '/wx/order/prepay',
		                        method: 'POST',
		                        header: {
		                            'content-type': 'application/json',
		                            'X-Token': uni.getStorageSync('token')
		                        },
		                        data: {
		                            orderId: orderId
		                        },
		                        success: (response) => {
		                            if (response.statusCode === 200 && response.data.errno === 0) {
		                                const payParams = response.data.data;
		                                // 调起支付
		                                uni.requestPayment({
		                                    provider: 'wxpay',
		                                    ...payParams,
		                                    success: (res) => {
		                                        uni.showToast({
		                                            title: '支付成功',
		                                            icon: 'success'
		                                        });
		                                        // 支付成功后跳转到订单详情页
		                                        uni.navigateTo({
		                                            url: `/pages/order/detail?orderId=${orderId}`
		                                        });
		                                    },
		                                    fail: (err) => {
		                                        console.error('支付失败:', err);
		                                        // 支付失败也跳转到订单详情页，让用户可以重新支付
		                                        uni.navigateTo({
		                                            url: `/pages/order/detail?orderId=${orderId}&payStatus=fail`
		                                        });
		                                    }
		                                });
		                            } else {
		                                uni.showToast({
		                                    title: response.data.errmsg || '获取支付参数失败',
		                                    icon: 'none'
		                                });
		                            }
		                        },
		                        fail: (error) => {
		                            console.error('获取支付参数失败:', error);
		                            uni.showToast({
		                                title: '获取支付参数失败',
		                                icon: 'none'
		                            });
		                        }
		                    });
		                },
        goBack() {
            uni.navigateBack();
        },
        async loadHistoryMessages() {
            if (this.chatInfo?.sellerId) {
                try {
                    const [error, res] = await messageApi.getHistory(this.chatInfo.sellerId);
                    
                    if (!error && res.data.errno === 0) {
                        const messages = res.data.data.map(msg => ({
                            type: msg.type,
                            content: msg.content,
                            url: msg.type === 'image' ? msg.content : undefined,
                            time: msg.createTime,
                            isSelf: msg.fromUserId === uni.getStorageSync('userId')
                        }));
                        
                        this.messageList = [...messages, ...this.messageList];
                        this.saveMessages();
                        this.scrollToBottom();
                    } else {
                        // 如果接口调用失败，尝试从本地加载
                        const key = `chat_history_${this.chatInfo.sellerId}`;
                        const history = uni.getStorageSync(key) || [];
                        this.messageList = [...history, ...this.messageList];
                        this.scrollToBottom();
                    }
                } catch (error) {
                    console.error('加载历史消息失败:', error);
                    // 从本地加载
                    const key = `chat_history_${this.chatInfo.sellerId}`;
                    const history = uni.getStorageSync(key) || [];
                    this.messageList = [...history, ...this.messageList];
                    this.scrollToBottom();
                }
            }
        },
        async sendMessage() {
            if (!this.messageText.trim()) return;
            
            const messageData = {
                toUserId: this.chatInfo.sellerId,
                type: 'text',
                content: this.messageText,
                productId: this.chatInfo?.productInfo?.id || ''
            };
            
            try {
                const [error, res] = await messageApi.send(messageData);
                
                if (!error && res.data.errno === 0) {
                    const newMessage = {
                        type: 'text',
                        content: this.messageText,
                        time: new Date().getTime(),
                        isSelf: true
                    };
                    
                    this.messageList.push(newMessage);
                    this.saveMessages();
                    this.messageText = '';
                    this.scrollToBottom();
                    this.updateChatList();
                } else {
                    uni.showToast({
                        title: '发送失败',
                        icon: 'none'
                    });
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                uni.showToast({
                    title: '发送失败',
                    icon: 'none'
                });
            }
        },
        async chooseImage() {
            uni.chooseImage({
                count: 1,
                success: async (res) => {
                    const tempFilePath = res.tempFilePaths[0];
                    
                    // 显示上传中状态
                    const newMessage = {
                        type: 'image',
                        url: tempFilePath,
                        time: new Date().getTime(),
                        isSelf: true,
                        status: 'uploading'
                    };
                    
                    this.messageList.push(newMessage);
                    this.scrollToBottom();
                    
                    try {
                        // 上传图片
                        const [uploadError, uploadRes] = await messageApi.uploadImage(tempFilePath);
                        
                        if (!uploadError && uploadRes.statusCode === 200) {
                            const uploadData = JSON.parse(uploadRes.data);
                            if (uploadData.errno === 0) {
                                // 发送图片消息
                                const messageData = {
                                    toUserId: this.chatInfo.sellerId,
                                    type: 'image',
                                    content: uploadData.data.url,
                                    productId: this.chatInfo?.productInfo?.id || ''
                                };
                                
                                const [sendError, sendRes] = await messageApi.send(messageData);
                                
                                if (!sendError && sendRes.data.errno === 0) {
                                    newMessage.url = uploadData.data.url;
                                    newMessage.status = 'success';
                                } else {
                                    newMessage.status = 'failed';
                                }
                            } else {
                                newMessage.status = 'failed';
                            }
                        } else {
                            newMessage.status = 'failed';
                        }
                    } catch (error) {
                        console.error('发送图片消息失败:', error);
                        newMessage.status = 'failed';
                    }
                    
                    this.saveMessages();
                    this.updateChatList();
                }
            });
        },
        saveMessages() {
            if (this.chatInfo?.sellerId) {
                const key = `chat_history_${this.chatInfo.sellerId}`;
                uni.setStorageSync(key, this.messageList);
            }
        },
        updateChatList() {
            const lastMessage = this.messageList[this.messageList.length - 1];
            const chatInfo = {
                sellerId: this.chatInfo.sellerId,
                sellerName: this.chatInfo.sellerName,
                sellerAvatar: this.chatInfo.sellerAvatar,
                lastMessage: lastMessage.type === 'text' ? lastMessage.content : '[图片]'
            };
            
            // 获取消息列表页面实例并更新
            const pages = getCurrentPages();
            const messageListPage = pages.find(page => page.route === 'pages/message/messageList');
            if (messageListPage) {
                messageListPage.$vm.addNewChat(chatInfo);
            }
        },
        scrollToBottom() {
            setTimeout(() => {
                const query = uni.createSelectorQuery().in(this);
                query.select('.message-list').boundingClientRect(data => {
                    this.scrollTop = data.height * 2;
                }).exec();
            }, 100);
        },
        previewImage(url) {
            uni.previewImage({
                urls: [url],
                current: url
            });
        },
        loadMoreMessages() {
            console.log('加载更多消息');
        }
    }
};
</script>

<style>
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f5f5f5;
}

.chat-header {
    padding: 10px;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
    padding-top: 40px;
}

.back-button {
    padding: 5px 10px;
    font-size: 14px;
}

.chat-name {
    flex: 1;
    text-align: center;
    font-size: 16px;
    margin-right: 30px;
}

.message-list {
    flex: 1;
    padding: 10px 15px;
    padding-bottom: 100px;
}

.product-card {
    display: flex;
    padding: 20rpx;
    background-color: #f8f8f8;
    border-radius: 12rpx;
    margin: 20rpx;
}

.product-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
}

.product-info {
    flex: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.product-name {
    font-size: 28rpx;
    color: #333;
}

.product-price {
    font-size: 32rpx;
    color: #ff6b6b;
    font-weight: bold;
}

.order-btn {
    width: 160rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    background-color: #ff6b6b;
    color: #ffffff;
    font-size: 24rpx;
    border-radius: 30rpx;
    margin-top: 10rpx;
}

.order-btn:active {
    opacity: 0.8;
}

.message-item {
    display: flex;
    margin-bottom: 20px;
    align-items: flex-start;
}

.message-self {
    flex-direction: row-reverse;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: 1px solid #eee;
}

.message-content {
    max-width: 70%;
    margin: 0 10px;
}

.text-message {
    padding: 12px 16px;
    border-radius: 18px;
    background-color: #fff;
    word-break: break-all;
    font-size: 16px;
    line-height: 1.4;
}

.message-self .text-message {
    background-color: #95ec69;
}

.image-message {
    max-width: 200px;
    border-radius: 4px;
}

.input-area {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding-bottom: env(safe-area-inset-bottom);
}

.input-container {
    display: flex;
    align-items: flex-end;
    padding: 10px 15px;
    border-top: 1px solid #eee;
    background-color: #fff;
}

.message-input {
    flex: 1;
    min-height: 36px;
    max-height: 120px;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-right: 10px;
    font-size: 16px;
    line-height: 20px;
    background-color: #f8f8f8;
}

.button-group {
    display: flex;
    align-items: center;
}

.icon-button {
    padding: 8px 12px;
    margin-right: 8px;
    background: #f5f5f5;
    border-radius: 4px;
    font-size: 14px;
}

.send-button {
    padding: 8px 15px;
    background: #ddd;
    color: #fff;
    border-radius: 4px;
    font-size: 14px;
}

.send-button.active {
    background: #07c160;
}
</style>